/**
 * 统一封装请求工具
 */
const httpUtils = {

	/**
	 * get请求封装
	 */
	get: (obj) => {
		// 处理请求头
		const token = uni.getStorageSync('token');
		if(!obj.header) {
			obj.header = {};
		}
		obj.header['Tancire-Source'] = '1';
		if (token) {
			if (!obj.noAuth) {
				obj.header['Authorization'] = 'Bearer ' + token;
			}
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: obj.url,
				method: "GET",
				data: obj.data,
				timeout: 120000,
				header: obj.header,
				success: (res) => {
					if (res.statusCode === 200) {
						if (res.data && res.data.code === 500) {
							reject(res);
						}
						if (res.data && res.data.code === 401) {
							// 认证失败，重新登录
							uni.removeStorageSync('token');
							uni.removeStorageSync('userInfo');
						}
						resolve(res.data);
					} else {
						reject(res);
					}
				},
				fail: (err) => {
					if (err.errMsg === 'request:fail' && !err.response) {
						uni.showToast({
							title: '网络连接超时',
							icon: 'none',
							duration: 1500
						});
						uni.removeStorageSync('token');
						uni.removeStorageSync('userInfo');
					}
					reject(err);
				}
			});
		});
	},

	/**
	 * post请求封装
	 */
	post: (obj) => {
		const token = uni.getStorageSync('token');
		if(!obj.header) {
			obj.header = {};
		}
		obj.header['Tancire-Source'] = '1';
		if (token) {
			if (!obj.noAuth) {
				obj.header['Authorization'] = 'Bearer ' + token;
			}
		}
		if (!obj.header['content-type']) {
			// 默认json格式请求
			obj.header['content-type'] = 'application/json'; 
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: obj.url,
				method: "POST",
				data: obj.data,
				timeout: 120000,
				header: obj.header,
				success: (res) => {
					if (res.statusCode === 200) {
						if (res.data && res.data.code === 500) {
							reject(res);
						}
						if (res.data && res.data.code === 401) {
							// 认证失败，重新登录
							uni.removeStorageSync('token');
							uni.removeStorageSync('userInfo');
						}
						resolve(res.data);
					} else if (res.statusCode === 401) {
						reject(res);
					} else {
						reject(res);
					}
				},
				fail: (err) => {
					if (err.errMsg === 'request:fail' && !err.response) {
						uni.showToast({
							title: '网络连接失败',
							icon: 'none',
							duration: 1500
						});
						uni.removeStorageSync('token');
						uni.removeStorageSync('userInfo');
					}
					reject(err);
				}
			});
		});
	},
}

export default httpUtils;
